"use strict"

const Service = require('egg').Service
const moment = require('moment')

class GoodsSercide extends Service {
    /**
     * 商品查询
     * @param {商品查询} param 
     * title(商品名称-否),category_id(分类id-否),brand_id(品牌id-否),page(页码),rows(条数)
     */
    async list(param) {
        const { app, ctx } = this
        let where = {}
        if(param.title){
            where.title = param.title
        }
        if(param.category_id){
            where.category_id = JSON.stringify(param.category_id)
        }
        if(param.brand_id){
            where.brand_id = param.brand_id
        }
        try{
            let result = await app.model.Goods.findAndCountAll({
                where,
                limit: Number(param.rows),
                offset: (param.page - 1) * param.rows,
                include: [
                    {
                        model: app.model.Brand  ,
                        attributes: ['name']
                    }
                ],
                distinct: true
            })
            // 品牌列表
            const brand_list = await app.model.Brand.findAll({
                attributes: ['id', 'name']
            })
            result.brand_list = brand_list
            // 分类列表
            const category_list = await app.model.Category.findAll({
                include: [
                    {
                        model: app.model.Category,
                        as: 'children',
                        attributes: ['id', 'name'],
                    }
                ],
                attributes: ['id', 'name']
            })
            result.category_list = category_list
            
            // 分类名称
            for(let i=0; i < result.rows.length; i++){
                // 分类查询
                let category_name = ''
                for(let k=0; k < result.rows[i].category_id.length; k++){
                    let id = result.rows[i].category_id[k]
                    let category_res = await app.model.Category.findOne({
                        where: { id },
                        attributes: ['name']
                    })
                    if(k == result.rows[i].category_id.length-1){
                        category_name += category_res.name
                    }else{
                        category_name += category_res.name + '/'
                    }                    
                }
                result.rows[i].setDataValue('category_name', category_name)
            }

            return ctx.app.returnHint(result, '查询成功').definedSucceed
        }catch(err){
            console.log(err)
            return ctx.app.returnHint(err, '查询失败').definedError
        }
    }

    /**
     * 
     * @param {商品详情} param 
     *  id(商品id)
     */
    async details(param) {
        const { app, ctx } = this
        const id = param.id
        try{
            let result = await app.model.Goods.findOne({
                where: {id},
                include: [
                    {
                        model: app.model.GoodsImgs,
                        as: 'imgs',
                        attributes: ['img_path'],
                    },
                    {
                        model: app.model.AttributeKey,
                        as: 'attributeList',
                        attributes: ['name'],
                        include: [
                            {
                                model: app.model.AttributeValue,
                                as: 'children',
                                attributes: ['value'],
                            },
                        ]
                    },
                    {
                        model: app.model.GoodsSku,
                        as: 'goods_specs',
                        attributes: ['attribute_specs', 'sales_price', 'price', 'inventory'],
                    },
                ]
            })

            return ctx.app.returnHint(result, '查询成功').definedSucceed
        }catch(err) {
            console.log(err)
            return ctx.app.returnHint(err, '查询失败').definedError
        }
    }
    
    /**
     * 
     * @param {新增商品} param 
     * title(标题),brand_id(品牌id),category_id(分类id),body(详情)
     * img(缩略图),imgs(轮播图),sales_price(销售价),price(活动价),inventory(库存)
     * discount(折扣),serial_number(编号),attributeList(属性列表),goods_specs(商品属性组合)
     */
    async add(param) {
        const { app, ctx } = this
        const transaction = await app.model.transaction(); // 开始事务
        try {
            const data = {
                title: param.title,
                img: param.img,
                new: param.new,
                brand_id: param.brand_id,
                category_id: param.category_id,
                sales_price: param.sales_price,
                price: param.price,
                inventory: param.inventory,
                discount: param.discount,
                serial_number: param.serial_number,
                body: param.body,
                create_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            // 创建商品信息数据
            const result = await app.model.Goods.create(data, {
                transaction: transaction
            })
            const goods_id = result.id
            // 保存轮播图
            const url_imgs = []
            for(let img_path of param.imgs){
                url_imgs.push({
                    goods_id,
                    img_path: img_path,
                    create_time: moment().format('YYYY-MM-DD HH:mm:ss')
                })
            }
            await app.model.GoodsImgs.bulkCreate(url_imgs, {
                transaction
            })

            /**
             * 
             * 添加属性、属性值
             */
            const attrValArray = []
            for(let item of param.attributeList){
                // 属性
                let attrArray = {
                    goods_id,
                    name: item.name,
                    create_time: moment().format('YYYY-MM-DD ')
                }
                //添加属性
                let attrKey = await app.model.AttributeKey.create(attrArray, {
                    transaction
                })
                // 属性值
                for(let val of item.children){
                    attrValArray.push({
                        attribute_id: attrKey.id,
                        value: val,
                        create_time: moment().format('YYYY-MM-DD ')
                    })
                }
            }
            //添加属性值
            await app.model.AttributeValue.bulkCreate(attrValArray, {
                transaction
            })

            /**
             * 添加商品关联属性组合
             */
            const goodsSpecsArray = []
            for(let item of param.goods_specs) {
                goodsSpecsArray.push({
                    goods_id,
                    attribute_specs: JSON.stringify(item.attribute_specs),
                    sales_price: item.sales_price,
                    price: item.price,
                    inventory: item.inventory,
                    create_time: moment().format('YYYY-MM-DD ')
                })
            }
            await app.model.GoodsSku.bulkCreate(goodsSpecsArray, {
                transaction
            })
            // 事务提交
            await transaction.commit();
            return ctx.app.returnHint(result, '添加成功').definedSucceed

        }catch(err) {
            console.log(err)
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '添加失败').definedError
        }
    }
    /**
     * 
     * @param {编辑商品} param 
     * id(商品id),
     * 
     */
    async redact(param) {
        const { app, ctx } = this
        const transaction = await app.model.transaction(); // 开始事务
        try {
            const data = {
                title: param.title,
                img: param.img,
                new: param.new,
                brand_id: param.brand_id,
                category_id: param.category_id,
                sales_price: param.sales_price,
                price: param.price,
                inventory: param.inventory,
                discount: param.discount,
                serial_number: param.serial_number,
                body: param.body,
                update_time: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            // 更新商品信息数据
            const result = await app.model.Goods.update(data, {
                where: { id: param.id },
                transaction: transaction
            })
            // 商品id
            const goods_id = param.id || result.id

            /**
             * 查询 轮播图是否存在
             */
                const imgs_result = await app.model.GoodsImgs.findAll({
                    where: { goods_id }
                })
                // 如果存在就删除旧的轮播图路径
                await app.model.GoodsImgs.destroy({
                    where: { goods_id },
                    transaction,
                    limit: imgs_result.length
                })
                // 重新保存轮播图
                const url_imgs = []
                for(let img_path of param.imgs){
                    url_imgs.push({
                        goods_id,
                        img_path: img_path,
                        create_time: moment().format('YYYY-MM-DD HH:mm:ss')
                    })
                }
                await app.model.GoodsImgs.bulkCreate(url_imgs, {
                    transaction
                })

            /**
             * 
             * 添加属性、属性值
             */
                // 查询 属性是否存在
                const attr_result = await app.model.AttributeKey.findAll({
                    where: { goods_id }
                })
                // 删除旧属性
                await app.model.AttributeKey.destroy({
                    where: { goods_id },
                    transaction,
                    limit: attr_result.length
                })
                for(let item of attr_result){
                    // 查询 属性值是否存在
                    const attr_val_result = await app.model.AttributeValue.findAll({
                        where: { attribute_id: item.id }
                    })
                    // 删除属性值
                    await app.model.AttributeValue.destroy({
                        where: { attribute_id: item.id },
                        transaction,
                        limit: attr_val_result.length
                    })
                }
                // 重新添加属性和属性值
                const attrValArray = []
                for(let item of param.attributeList){
                    // 属性
                    let attrArray = {
                        goods_id,
                        name: item.name,
                        create_time: moment().format('YYYY-MM-DD ')
                    }
                    //添加属性
                    let attrKey = await app.model.AttributeKey.create(attrArray, {
                        transaction
                    })
                    // 属性值
                    for(let val of item.children){
                        attrValArray.push({
                            attribute_id: attrKey.id,
                            value: val,
                            create_time: moment().format('YYYY-MM-DD ')
                        })
                    }
                }
                //添加属性值
                await app.model.AttributeValue.bulkCreate(attrValArray, {
                    transaction
                })

            /**
             *  查询 属性组合是否存在
             */
                const goods_specs_result = await app.model.GoodsSku.findAll({
                    where: { goods_id }
                })
                // 删除旧的数据
                await app.model.GoodsSku.destroy({
                    where: { goods_id },
                    transaction,
                    limit: goods_specs_result.length
                })
                // 添加新的数据
                const goodsSpecsArray = []
                for(let item of param.goods_specs) {
                    goodsSpecsArray.push({
                        goods_id,
                        attribute_specs: JSON.stringify(item.attribute_specs),
                        sales_price: item.sales_price,
                        price: item.price,
                        inventory: item.inventory,
                        create_time: moment().format('YYYY-MM-DD ')
                    })
                }
                await app.model.GoodsSku.bulkCreate(goodsSpecsArray, {
                    transaction
                })
            // 事务提交
            await transaction.commit();
            return ctx.app.returnHint(result, '更新成功').definedSucceed

        }catch(err) {
            console.log(err)
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '更新失败').definedError
        }
    }

     /**
     * @param {删除商品} param 
     * id(商品id)
     */
    async del(param) {
        const { app, ctx } = this
        const transaction = await app.model.transaction(); // 开始事务
        const id = param.id
        try{
            // 删除商品信息
            let result = await app.model.Goods.destroy({
                where: { id },
                transaction
            })
            // 删除轮播图
            const imgs_result = await app.model.GoodsImgs.findAll({
                where: { goods_id: id }
            })
            if(imgs_result.length) {
                for(let item of imgs_result){
                    await app.model.GoodsImgs.destroy({
                        where: { id: item.id },
                        transaction
                    })
                }
            }
            // 删除属性是否存在
            const attr_result = await app.model.AttributeKey.findAll({
                where: { goods_id: id }
            })
            if(attr_result.length) {
                for(let item of attr_result){
                    await app.model.AttributeKey.destroy({
                        where: { id: item.id },
                        transaction
                    })
                    // 查询 属性值是否存在
                    const attr_val_result = await app.model.AttributeValue.findAll({
                        where: { attribute_id: item.id }
                    })
                    if(attr_val_result.length) {
                        for(let col of attr_val_result){
                            await app.model.AttributeValue.destroy({
                                where: { id: col.id },
                                transaction
                            })
                        }
                    }
                }
            }
            // 删除属性组合是否存在
            const goods_specs_result = await app.model.GoodsSku.findAll({
                where: { goods_id: id }
            })
            if(goods_specs_result.length) {
                for(let item of goods_specs_result){
                    await app.model.GoodsSku.destroy({
                        where: { id: item.id },
                        transaction
                    })
                }
            }

            // 事务提交
            await transaction.commit();
            return ctx.app.returnHint(result, '删除成功').definedSucceed
        }catch(err){
            console.log(err)
            await transaction.rollback();// 捕获异常后回滚事务！！
            return ctx.app.returnHint(err, '删除失败').definedError
        }
    }

}   

module.exports = GoodsSercide

